// 通用权限检查类型
export type PermissionChecker = {
  page: (entity: string, action?: string) => boolean;
  list: (entity: string, action?: string) => boolean;
  get: (entity: string, action?: string) => boolean;
  insert: (entity: string, action?: string) => boolean;
  update: (entity: string, action?: string) => boolean;
  delete: (entity: string, action?: string) => boolean;
};

export type Access = {
  accessRouteFilter: any;
  has: (permission: string) => boolean;
  dw: PermissionChecker;
  sys: PermissionChecker;
  order: PermissionChecker;
  custom: (prefix: string) => PermissionChecker;
};

/**
 * @see https://umijs.org/docs/max/access#access
 * */
export default function access(initialState: { currentUser?: API.CurrentUser } | undefined): Access {
  const {currentUser} = initialState ?? {};
  const permissions = currentUser?.permissions ?? [];

  const hasPermission = (key: string) => permissions.includes(key);

  // 生成通用权限检查函数
  const genPermissionChecker = (prefix: string): PermissionChecker => ({
    page: (entity, action = "page") => hasPermission(`${prefix}:${entity}:${action}`),
    list: (entity, action = "list") => hasPermission(`${prefix}:${entity}:${action}`),
    get: (entity, action = "get") => hasPermission(`${prefix}:${entity}:${action}`),
    insert: (entity, action = "insert") => hasPermission(`${prefix}:${entity}:${action}`),
    update: (entity, action = "update") => hasPermission(`${prefix}:${entity}:${action}`),
    delete: (entity, action = "delete") => hasPermission(`${prefix}:${entity}:${action}`),
  });

  return {
    accessRouteFilter: (route: { permission?: any }) => {
      if (route.permission) {
        return currentUser?.permissions?.includes(route.permission);
      }
      return true;
    },
    has: (permission: string) => {
      return hasPermission(permission);
    },
    dw: genPermissionChecker("dw"),
    sys: genPermissionChecker("sys"),
    order: genPermissionChecker("order"),
    custom: genPermissionChecker, // 支持动态传入前缀
  };
}
